#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER_SIZE 100

/* 状态码 */
enum STATUS_CODE
{
    ON_SUCCESS,
    MALLOC_ERROR,
    NULL_PTR,
    INVALID_ACCESS,
};



/* 交换器 */
int swapNum(int *val1, int * val2)
{
    int tempVal = *val1;
    *val1 = *val2;
    *val2 = tempVal; 
}

/* 打印器 */
int printfElement( int *nums, int len)
{
    for(int idx = 0; idx < len; idx++)
    {
        printf("%d\t", nums[idx]);
    }
    printf("\n");
    return 0;
}

/* 判空 */
int judgEmpt(int *judg)
{
    if(judg == NULL)
    {
        return MALLOC_ERROR;
    }
    memset(judg, 0, sizeof(int)*1);
    return 0;
}

static int innerQuickSort(int *nums, int begin, int len);

static int innerQuickSort(int *nums, int begin, int len)
{
    if(len <= begin)
    {
        return 0;
    }
    /* 记录基准值 */
    int pivot = nums[begin];
    /* 备份begin 和len */
    int tmpBegin = begin;
    int tmpLen = len;

    while(begin < len)
    {
        while(begin < len)
        {
            /* 从右向左 */
            if(nums[len] >= pivot)
            {
                len--;
            }
            else
            {
                nums[begin++] = nums[len];
                break;
            }
        }

        while(begin < len)
        {
            /* 开始从左往右哦*/
            if(nums[begin] > pivot)
            {
                nums[len--] = nums[begin];
                break;
            }
            else
            {
                begin++;
            }
        }
    }
   // begin == len 时退出
    nums[begin] = pivot;
    innerQuickSort(nums, tmpBegin, begin-1);
    innerQuickSort(nums, begin+1, tmpLen);
    return 0;
}

int quickSort(int *nums, int len)
{
#if 0
    /* 定义两个指针变量 */
    int *pre = (int *)malloc(sizeof(int) * 1);
    judgEmpt(pre);
    int *cur = (int *)malloc(sizeof(int) * 1);
    /* 判空 */
    judgEmpt(cur);
    /* 键值 */
    int key = 0;
    // /* 长度 */
    // int len = (sizeof(nums) / sizeof(nums[0]));
    // printf("len:%d\n", len);
    /* 打印器 */
    printf("原数组");
    printfElement(nums, len);

    /* 键值为首元素 */
    key = nums[0];
    *pre = 0;
    for(int idx = 1; idx < len; idx++)
    {
        *cur = idx;
        //pre = cur - 1;
        if(nums[*cur] != nums[*pre] && nums[*cur] < key && pre++ != cur)
        {
            /* 交换器 */
            swapNum(&(nums[*cur]), &(nums[*pre]));
            pre++;
        }
    }
    printfElement(nums, len);
#endif
    if(nums == NULL)
    {
        return 0;
    }
    /* 指定范围查 */
    return innerQuickSort(nums, 0, len-1);//为啥-1
}

int main()
{
    int nums[] = {66, 22, 11, 44, 25, 88, 99, 10};
    /* 为什么长度在被调函数中求不出来 */
    int len = (sizeof(nums) / sizeof(nums[0]));
    printf("len:%d\n", len);
    quickSort(nums, len);
    printfElement(nums, len);

    return 0;
}